package com.smartbus.bus.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.smartbus.common.annotation.Log;
import com.smartbus.common.core.controller.BaseController;
import com.smartbus.common.core.domain.AjaxResult;
import com.smartbus.common.enums.BusinessType;
import com.smartbus.bus.domain.StationDistance;
import com.smartbus.bus.domain.TransferRoute;
import com.smartbus.bus.service.TransferPathService;
import com.smartbus.bus.mapper.StationDistanceMapper;
import com.smartbus.common.utils.poi.ExcelUtil;
import com.smartbus.common.core.page.TableDataInfo;

/**
 * 换乘查询Controller
 *
 * @author smartbus
 * @date 2024-09-24
 */
@RestController
@RequestMapping("/bus/transfer")
public class TransferController extends BaseController
{
    @Autowired
    private TransferPathService transferPathService;

    @Autowired
    private StationDistanceMapper stationDistanceMapper;

    /**
     * 换乘路径查询
     */
    @GetMapping("/search")
    public AjaxResult searchTransfer(
            @RequestParam Integer fromStationId,
            @RequestParam Integer toStationId,
            @RequestParam(defaultValue = "default") String mode)
    {
        try {
            if (fromStationId == null || toStationId == null) {
                return error("起始站点和目标站点不能为空");
            }

            if (fromStationId.equals(toStationId)) {
                return error("起始站点和目标站点不能相同");
            }

            TransferRoute result = transferPathService.searchTransferRoute(fromStationId, toStationId, mode);

            if (result == null) {
                return error("未找到换乘方案");
            }

            if (result.getTransferPlans() == null || result.getTransferPlans().isEmpty()) {
                return error("暂无可用的换乘路线，请检查线路配置或选择其他站点");
            }

            return success(result);
        } catch (Exception e) {
            logger.error("换乘查询失败", e);
            return error("换乘查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询站点间距离预计算列表
     */
    @PreAuthorize("@ss.hasPermi('bus:transfer:list')")
    @GetMapping("/distances")
    public TableDataInfo getDistancesList(StationDistance stationDistance)
    {
        startPage();
        List<StationDistance> list = stationDistanceMapper.selectStationDistanceList(stationDistance);
        return getDataTable(list);
    }

    /**
     * 查询可步行换乘的站点对
     */
    @GetMapping("/walkable")
    public AjaxResult getWalkableStations()
    {
        List<StationDistance> list = stationDistanceMapper.selectWalkableDistances();
        return success(list);
    }

    /**
     * 查询指定站点的可换乘站点
     */
    @GetMapping("/transferable/{fromStationId}")
    public AjaxResult getTransferableStations(@PathVariable Integer fromStationId)
    {
        List<StationDistance> list = stationDistanceMapper.selectTransferableStations(fromStationId);
        return success(list);
    }

    /**
     * 查询两个站点间的距离
     */
    @GetMapping("/distance/{fromStationId}/{toStationId}")
    public AjaxResult getDistanceBetweenStations(
            @PathVariable Integer fromStationId,
            @PathVariable Integer toStationId)
    {
        StationDistance distance = stationDistanceMapper.selectDistanceBetweenStations(fromStationId, toStationId);
        if (distance == null) {
            return error("未找到站点间距离信息");
        }
        return success(distance);
    }

    /**
     * 重新计算站点间距离
     */
    @PreAuthorize("@ss.hasPermi('bus:transfer:recalculate')")
    @Log(title = "站点间距离", businessType = BusinessType.UPDATE)
    @PostMapping("/recalculate")
    public AjaxResult recalculateStationDistances()
    {
        try {
            int result = stationDistanceMapper.recalculateStationDistances();
            if (result > 0) {
                return success("站点间距离重新计算完成");
            } else {
                return error("站点间距离计算失败");
            }
        } catch (Exception e) {
            logger.error("重新计算站点间距离失败", e);
            return error("重新计算站点间距离失败：" + e.getMessage());
        }
    }

    /**
     * 获取指定站点ID的详细信息
     */
    @GetMapping("/station/{stationId}")
    public AjaxResult getStationDetail(@PathVariable Integer stationId)
    {
        StationDistance queryParam = new StationDistance();
        queryParam.setFromStationId(stationId);
        List<StationDistance> distances = stationDistanceMapper.selectStationDistanceList(queryParam);
        return success(distances);
    }

    /**
     * 清空距离预计算表（危险操作，需要管理员权限）
     */
    @PreAuthorize("@ss.hasPermi('bus:transfer:clear')")
    @Log(title = "站点间距离", businessType = BusinessType.DELETE)
    @DeleteMapping("/clear")
    public AjaxResult clearStationDistances()
    {
        try {
            int result = stationDistanceMapper.truncateStationDistances();
            return success("距离预计算表已清空，请重新计算");
        } catch (Exception e) {
            logger.error("清空距离预计算表失败", e);
            return error("清空距离预计算表失败：" + e.getMessage());
        }
    }

    /**
     * 导出站点间距离数据
     */
    @PreAuthorize("@ss.hasPermi('bus:transfer:export')")
    @Log(title = "站点间距离", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, StationDistance stationDistance)
    {
        List<StationDistance> list = stationDistanceMapper.selectStationDistanceList(stationDistance);
        ExcelUtil<StationDistance> util = new ExcelUtil<StationDistance>(StationDistance.class);
        util.exportExcel(response, list, "站点间距离数据");
    }

    /**
     * 换乘路径搜索（POST方式，支持更复杂的查询参数）
     */
    @PostMapping("/search")
    public AjaxResult searchTransferPost(@RequestBody TransferSearchRequest request)
    {
        try {
            if (request.getFromStationId() == null || request.getToStationId() == null) {
                return error("起始站点和目标站点不能为空");
            }

            if (request.getFromStationId().equals(request.getToStationId())) {
                return error("起始站点和目标站点不能相同");
            }

            String mode = request.getMode() != null ? request.getMode() : "default";
            TransferRoute result = transferPathService.searchTransferRoute(
                request.getFromStationId(), request.getToStationId(), mode
            );

            if (result == null) {
                return error("未找到换乘方案");
            }

            if (result.getTransferPlans() == null || result.getTransferPlans().isEmpty()) {
                return error("暂无可用的换乘路线，请检查线路配置或选择其他站点");
            }

            return success(result);
        } catch (Exception e) {
            logger.error("换乘查询失败", e);
            return error("换乘查询失败：" + e.getMessage());
        }
    }

    /**
     * 换乘搜索请求对象
     */
    public static class TransferSearchRequest {
        private Integer fromStationId;
        private Integer toStationId;
        private String mode;

        public Integer getFromStationId() { return fromStationId; }
        public void setFromStationId(Integer fromStationId) { this.fromStationId = fromStationId; }
        public Integer getToStationId() { return toStationId; }
        public void setToStationId(Integer toStationId) { this.toStationId = toStationId; }
        public String getMode() { return mode; }
        public void setMode(String mode) { this.mode = mode; }
    }
}